package gofish.json;

import java.util.ArrayList;

/**
 * AbstractCompositeJson is the parent class of all composite types of the
 * AbstractJson family.  Its children will each have an ArrayList of AbstractJson
 * elements.
 * This class's only requirement is that its children declare what their startSymbol
 * and endSymbol are in their constructors.
 * @author Matt Lauber
 *
 */
public abstract class AbstractCompositeJson extends AbstractJson {

	protected ArrayList<AbstractJson> elements;
	private String startSymbol;
	private String endSymbol;
	
	/**
	 * 
	 * @param startSymbol : for JsonObject this will be "{" and for JsonArray this will be "[".
	 * @param endSymbol : for JsonObject this will be "}" and for JsonArray this will be "]".
	 */
	public AbstractCompositeJson(String startSymbol, String endSymbol) {
		this.startSymbol = startSymbol;
		this.endSymbol = endSymbol;
		elements = new ArrayList<AbstractJson>();
	}
	
	/**
	 * This is overridden so that it returns a String containing the concatenation of
	 * a toString() call on each element in its ArrayList, enclosed in this object's
	 * startSymbol and endSymbol.
	 */
	public String toString() {
		
		if (elements.isEmpty()) {
			return startSymbol + endSymbol;
		}
		
		StringBuilder response = new StringBuilder();
		response.append( startSymbol ) 
				.append( elements.get(0).toString() );
		
		for (int i = 1; i < elements.size(); ++i) {
			response.append(",").append(elements.get(i).toString());
		}
		
		response.append( endSymbol );
		
		return response.toString();
	}

}
